package cn.crdeng.controller;

import cn.crdeng.Service.BlogService;
import cn.crdeng.Service.CommentService;
import cn.crdeng.po.Blog;
import cn.crdeng.po.Comment;
import cn.crdeng.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private BlogService blogService;
    @Value("${comment.acatar}")
    private String acatar;
    @Autowired
    private CommentService commentService;

    //查询留言
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.lsitCommentsByBlogId(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String saveCommtnts(Comment comment, HttpSession session) {
        Long BlogId = comment.getBlog().getId();
        Blog blogByID = blogService.getBlogByID(BlogId);
        User user = (User) session.getAttribute("user");
        if (user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar(acatar);
        }
        comment.setBlog(blogByID);
        commentService.saveComment(comment);
        return "redirect:/comments/" + BlogId;
    }

}
